const {
	getTime,
} = require('../../dateUtils')
const {
	getRandomId,
} = require('../../dbUtils')
const {
	getModuleTree,
} = require('./utils')

const _cmsMongo = global._cmsMongo

module.exports = {

	/**
	 * 权限树结构
	 * @param  {[type]} params [description]
	 * @return {[type]}        [description]
	 */
	funcList: async function(params) {
		let moduleFuncMap = {}
		let funcCol = await _cmsMongo.getCollection('func')
		let moduleList = await getModuleTree()
		let funcList = await funcCol.find({}, {
			create_time: 0,
			modify_time: 0,
		}).toArray()
		for (let i = 0; i < funcList.length; i++) {
			let func = funcList[i]
			moduleFuncMap[func.module_id] = moduleFuncMap[func.module_id] || {}
			moduleFuncMap[func.module_id][func.func_id] = func
		}
		let children = parseModuleTree(moduleList, moduleFuncMap)
		return [{
			id: 'root',
			name: 'root',
			children,
		}]
	},

	funcAdd: async function(params) {
		let {
			type,
			modify,
			p_id,
			id,
			name,
			url,
			desc = '',
		} = params
		// 添加模块
		let col = await _cmsMongo.getCollection(type)
		if (id) {
			let result = await col.findOne({
				[`${type}_id`]: id
			})
			if (result && result._id)
				return type == 'module' ? -1 : -2
		}
		id = id || getRandomId(8)
		let add = {
			[`${type}_id`]: id,
			[`${type}_name`]: name,
			desc,
			create_time: getTime(),
			modify_time: getTime(),
		}
		if (type == 'module') {
			add.parent_id = p_id || 0
			add.route = url
			if (!url)
				add.children = []
			if (p_id != 0) {
				await col.findOneAndUpdate({
					module_id: p_id,
				}, {
					$addToSet: {
						children: id,
					},
				})
			}
		} else if (type == 'func') {
			// 添加功能
			add.func_url = url
			add.module_id = p_id
		}
		return col.insertOne(add)
	},

	funcModify: async function(params) {
		let {
			type,
			id,
			name,
			url,
			desc,
		} = params
		// 修改信息
		let col = await _cmsMongo.getCollection(type)
		let query = {
			[`${type}_id`]: id,
		}
		let set = {
			[`${type}_name`]: name,
			desc,
			modify_time: getTime(),
		}
		if (type == 'module') {
			set.route = url
		} else {
			set.func_url = url
		}
		let {
			value
		} = await col.findOneAndUpdate(query, {
			$set: set,
		})
		return value
	},

	funcDel: async function(params) {
		let {
			type,
			id,
		} = params
		let funcCol = await _cmsMongo.getCollection('func')
		let moduleCol = await _cmsMongo.getCollection('module')
		if (type == 'func') {
			let func = await funcCol.findOne({
				func_id: id,
			})
			if (func && func.is_base == 1)
				return -3
			return funcCol.deleteOne({
				func_id: id,
			})
		}
		let module = await moduleCol.findOne({
			module_id: id
		})
		if (!module)
			return 1
		if (module.is_base == 1)
			return -3
		let func = await funcCol.findOne({
			module_id: id,
		})
		// 模块下有权限
		if (func && func._id)
			return -1
		// 有子模块
		if (Array.isArray(module.children) && module.children.length > 0)
			return -2
		let parentModule = await moduleCol.findOne({
			module_id: module.parent_id,
		})
		if (parentModule && Array.isArray(parentModule.children)) {
			let children = parentModule.children
			let idx = children.indexOf(id)
			children.splice(idx, 1)
			await moduleCol.findOneAndUpdate({
				module_id: module.parent_id,
			}, {
				$set: {
					children,
				}
			})
		}
		return moduleCol.deleteOne({
			module_id: id,
		})
	},

	/**
	 * 节点/模块下拉菜单
	 * @param  {[type]} params [description]
	 * @return {[type]}        [description]
	 */
	funcModule: async function(params) {
		let moduleList = await getModuleTree()
		let nodeData = [{
			id: '0',
			name: 'root',
			type: '节点',
		}]
		let moduleData = []
		parseModuleNode(moduleList, nodeData, moduleData)
		return {
			nodeData,
			moduleData,
		}
	},
}

function parseModuleTree(moduleList, moduleFuncMap) {
	for (let i = 0; i < moduleList.length; i++) {
		let module = moduleList[i]
		module.id = module.module_id
		module.name = module.module_name
		module.tree_url = module.route || ''
		module.type = '模块'
		if (Array.isArray(module.children)) {
			module.type = '节点'
			parseModuleTree(module.children, moduleFuncMap)
		} else {
			let funcMap = moduleFuncMap[module.module_id]
			if (funcMap) {
				module.children = Object.values(funcMap).map(val => {
					val.id = val.func_id
					val.name = val.func_name
					val.tree_url = val.func_url
					val.type = '权限'
					return val;
				})
			}
		}
	}
	return moduleList
}

function parseModuleNode(list, nodeData, moduleData) {
	for (let i = 0; i < list.length; i++) {
		let node = list[i]
		if (!node.route) {
			nodeData.push({
				id: node.module_id,
				name: node.module_name,
			})
		}
		if (Array.isArray(node.children))
			parseModuleNode(node.children, nodeData, moduleData)
		else
			moduleData.push({
				id: node.module_id,
				name: node.module_name,
			})

	}
}